<template>
  <div class="page-container">
    <div class="chat-container">
      <el-container>
        <!-- 左侧边栏 -->
        <el-aside width="250px">
          <div class="sidebar">
            <div class="buttons">
              <!-- 新对话按钮 -->
              <button class="new-chat-btn" @click="createNewChat">
                <i class="fas fa-plus"></i> 新对话
              </button>
              <!-- 角色扮演按钮 -->
              <button class="character-chat-btn" @click="goToCharacterChat">
                <i class="fas fa-theater-masks"></i> 角色扮演
              </button>
            </div>
            <div class="history-title">历史对话</div>
            <div class="conversation-list">
              <div v-for="chat in chatList" 
                   :key="chat.id" 
                   :class="['conversation-item', { active: currentChatId === chat.id }]"
                   @click="switchChat(chat.id)">
                <div class="conversation-content">{{ chat.firstMessage || '新对话' }}</div>
                <el-button
                  class="delete-btn"
                  type="danger"
                  size="small"
                  circle
                  @click.stop="confirmDelete(chat)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </div>
            <div class="logout-container">
              <el-button type="danger" plain @click="handleLogout">
                <el-icon><SwitchButton /></el-icon>
                退出登录
              </el-button>
            </div>
          </div>
        </el-aside>

        <!-- 主聊天区域 -->
        <el-main>
          <div class="chat-main">
            <!-- 消息列表 -->
            <div class="chat-messages" ref="messagesContainer">
              <div v-for="(message, index) in messages" :key="index" 
                :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']">
                <div class="message-content">
                  <pre v-if="message.role === 'assistant'" class="ai-content">{{ message.content }}</pre>
                  <div v-else>{{ message.content }}</div>
                  <!-- 添加附件显示 -->
                  <div v-if="message.attachments && message.attachments.length > 0" class="attachments">
                    <div v-for="attachment in message.attachments" :key="attachment.id" class="attachment-item">
                      <el-link :href="attachment.downloadUrl" target="_blank" type="primary">
                        <el-icon><Document /></el-icon>
                        {{ attachment.fileName }}
                      </el-link>
                      <span class="file-size">({{ formatFileSize(attachment.fileSize) }})</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 输入区域 -->
            <div class="input-container">
              <!-- 文件预览区域 -->
              <div class="upload-preview" v-if="selectedFiles.length > 0">
                <div v-for="(file, index) in selectedFiles" :key="index" class="file-item">
                  <span class="file-name">{{ file.name }}</span>
                  <el-button link class="delete-file" @click="removeFile(index)">
                    <el-icon><Close /></el-icon>
                  </el-button>
                </div>
              </div>

              <div class="input-wrapper">
                <el-input
                  v-model="inputMessage"
                  type="textarea"
                  :rows="3"
                  placeholder="说点什么吧..."
                  @keyup.enter.exact.prevent="sendMessage"
                />
                <div class="button-group">
                  <div class="left-buttons">
                    <el-upload
                      class="upload-button"
                      action=""
                      :auto-upload="false"
                      :show-file-list="false"
                      :on-change="handleFileChange"
                      :before-upload="() => false"
                      accept="image/*,.pdf,.doc,.docx,.txt"
                      multiple>
                      <el-button type="primary" plain>
                        <el-icon><Upload /></el-icon>
                        上传文件
                      </el-button>
                    </el-upload>
                  </div>
                  <el-button type="primary" :disabled="!canSend" @click="sendMessage">
                    发送
                  </el-button>
                </div>
              </div>
            </div>
          </div>
        </el-main>
      </el-container>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, onBeforeUnmount, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, SwitchButton, Delete, Document, Upload, Close } from '@element-plus/icons-vue'
import axios from 'axios'
import { useRouter } from 'vue-router'

const router = useRouter()
const inputMessage = ref('')
const messages = ref([])
const chatList = ref([])
const currentChatId = ref(null)
const messagesContainer = ref(null)
const isLoading = ref(false)
const selectedFiles = ref([])
const canSend = computed(() => inputMessage.value.trim() || selectedFiles.value.length > 0)

// 检查登录状态
const checkAuth = () => {
  const token = localStorage.getItem('token')
  if (!token) {
    router.push('/login')
  }
}

// 创建新对话
const createNewChat = async () => {
  try {
    const response = await axios.post('/api/chat/conversations', {
      title: '新对话'
    })
    chatList.value.unshift(response.data)
    currentChatId.value = response.data.id
    messages.value = []
  } catch (error) {
    ElMessage.error('创建对话失败')
  }
}

// 切换对话
const switchChat = async (chatId) => {
  currentChatId.value = chatId
  try {
    const response = await axios.get(`/api/chat/conversations/${chatId}/messages`)
    if (response.data) {
      messages.value = response.data
      // 找到用户的第一条消息作为标题
      const firstUserMessage = response.data.find(msg => msg.role === 'user')
      if (firstUserMessage) {
        const currentChat = chatList.value.find(chat => chat.id === chatId)
        if (currentChat) {
          currentChat.firstMessage = firstUserMessage.content
        }
      }
      await nextTick()
      scrollToBottom()
    }
  } catch (error) {
    console.error('获取对话消息失败:', error)
    ElMessage.error(error.response?.data?.message || '获取对话消息失败')
  }
}

// 处理文件选择
const handleFileChange = (file) => {
  // 检查文件大小（限制为10MB）
  const maxSize = 10 * 1024 * 1024 // 10MB
  if (file.raw.size > maxSize) {
    ElMessage.warning(`文件 ${file.raw.name} 太大，不能超过10MB`)
    return
  }
  selectedFiles.value.push(file.raw)
}

// 移除文件
const removeFile = (index) => {
  selectedFiles.value.splice(index, 1)
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 发送消息
const sendMessage = async () => {
  if (!canSend.value || isLoading.value) return
  
  const message = inputMessage.value.trim()
  const files = [...selectedFiles.value]
  inputMessage.value = ''
  selectedFiles.value = []
  isLoading.value = true

  try {
    // 如果是新对话,先创建对话
    if (!currentChatId.value) {
      const response = await axios.post('/api/chat/conversations', {
        title: '新对话'
      })
      currentChatId.value = response.data.id
      chatList.value.unshift(response.data)
    }

    // 立即显示用户消息
    const userMessageObj = {
      role: 'user',
      content: message,
      createdAt: new Date()
    }
    messages.value.push(userMessageObj)
    scrollToBottom()

    // 如果是新对话的第一条消息,更新对话列表中的标题
    if (messages.value.length === 1) {
      const currentChat = chatList.value.find(chat => chat.id === currentChatId.value)
      if (currentChat) {
        currentChat.firstMessage = message || '文件消息'
      }
    }

    let response
    if (files.length > 0) {
      try {
        // 使用FormData发送文件
        const formData = new FormData()
        formData.append('conversationId', currentChatId.value.toString())
        if (message) {
          formData.append('message', message)
        }
        files.forEach(file => {
          formData.append('files', file)
        })

        response = await axios.post('/api/chat/messages/attachment', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          timeout: 60000, // 设置较长的超时时间
          baseURL: import.meta.env.VITE_API_BASE_URL || 'http://localhost:8080'
        })
        
        // 更新用户消息中的附件信息
        if (response.data.attachments) {
          userMessageObj.attachments = response.data.attachments
        }
      } catch (uploadError) {
        console.error('文件上传失败:', uploadError)
        ElMessage.error('文件上传失败：' + (uploadError.response?.data?.message || '请检查文件大小和类型'))
        throw uploadError
      }
    } else {
      response = await axios.post('/api/chat/messages', {
        conversationId: currentChatId.value,
        message: message
      })
    }

    // 显示AI回复
    if (response.data.role === 'assistant') {
      messages.value.push({
        role: 'assistant',
        content: response.data.content,
        createdAt: new Date()
      })
      scrollToBottom()
    }

  } catch (error) {
    console.error('发送消息失败:', error)
    // 发送失败时移除之前添加的用户消息
    messages.value.pop()
    ElMessage.error(error.response?.data?.message || '发送消息失败')
  } finally {
    isLoading.value = false
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

// 处理登出
const handleLogout = () => {
  localStorage.removeItem('token')
  router.push('/login')
  ElMessage.success('已成功退出登录')
}

// 确认删除对话
const confirmDelete = async (chat) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这个对话吗？删除后无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    await deleteConversation(chat)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败：' + (error.response?.data?.message || '未知错误'))
    }
  }
}

// 删除对话
const deleteConversation = async (chat) => {
  try {
    await axios.delete(`/api/chat/conversations/${chat.id}`)
    chatList.value = chatList.value.filter(item => item.id !== chat.id)
    ElMessage.success('删除成功')
    
    // 如果删除的是当前对话，切换到列表中的第一个对话或清空消息
    if (currentChatId.value === chat.id) {
      if (chatList.value.length > 0) {
        switchChat(chatList.value[0].id)
      } else {
        currentChatId.value = null
        messages.value = []
      }
    }
  } catch (error) {
    throw error
  }
}

// 跳转到角色扮演页面
const goToCharacterChat = () => {
  router.push('/character-chat')
}

onMounted(async () => {
  checkAuth()
  try {
    const response = await axios.get('/api/chat/conversations')
    chatList.value = response.data
    // 获取每个对话的第一条消息
    for (const chat of chatList.value) {
      try {
        const messagesResponse = await axios.get(`/api/chat/conversations/${chat.id}/messages`)
        const firstUserMessage = messagesResponse.data.find(msg => msg.role === 'user')
        if (firstUserMessage) {
          chat.firstMessage = firstUserMessage.content
        }
      } catch (error) {
        console.error('获取对话消息失败:', error)
      }
    }
    if (chatList.value.length > 0) {
      switchChat(chatList.value[0].id)
    }
  } catch (error) {
    ElMessage.error('获取对话列表失败')
  }
})
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  height: 100vh;
  background-color: #f5f7fa;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  box-sizing: border-box;
  overflow: hidden;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
}

.chat-container {
  width: 900px;
  height: 600px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.el-container {
  height: 100%;
  overflow: hidden;
}

.el-aside {
  height: 100%;
  overflow: hidden;
  display: flex;
}

.sidebar {
  height: 100%;
  background-color: #f9fafb;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  width: 100%;
  overflow: hidden;
}

.buttons {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.new-chat-btn,
.character-chat-btn {
  flex: 1;
  padding: 10px;
  border: none;
  border-radius: 8px;
  background-color: #007bff;
  color: white;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 5px;
  transition: background-color 0.2s;
}

.character-chat-btn {
  background-color: #6c5ce7;
}

.new-chat-btn:hover {
  background-color: #0056b3;
}

.character-chat-btn:hover {
  background-color: #5f3dc4;
}

.history-title {
  padding: 0 16px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.conversation-list {
  flex-grow: 1;
  overflow-y: auto;
  padding: 0 8px;
  margin-right: -8px; /* 防止滚动条占用空间 */
}

.conversation-item {
  padding: 10px 16px;
  cursor: pointer;
  transition: background-color 0.2s;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.conversation-item:hover {
  background-color: #f3f4f6;
}

.conversation-item.active {
  background-color: #e5e7eb;
}

.conversation-content {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 8px;
}

.delete-btn {
  opacity: 0;
  transition: opacity 0.2s;
}

.conversation-item:hover .delete-btn {
  opacity: 1;
}

.chat-main {
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
  background-color: #f5f7fa;
  overflow: hidden;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  margin-right: -8px; /* 防止滚动条占用空间 */
}

.message {
  display: flex;
  margin-bottom: 15px;
  width: 100%;
}

.message-content {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 15px;
  word-wrap: break-word;
  white-space: pre-wrap;
  line-height: 1.4;
  font-size: 14px;
}

.user-message {
  justify-content: flex-end;
  
  .message-content {
    background-color: #95EC69;
    margin-right: 10px;
    border-top-right-radius: 4px;
  }
}

.ai-message {
  justify-content: flex-start;
  
  .message-content {
    background-color: #ffffff;
    margin-left: 10px;
    border-top-left-radius: 4px;
  }
}

.input-container {
  padding: 20px;
  background: white;
  border-top: 1px solid #e6e6e6;
}

.input-wrapper {
  width: 100%;
}

.el-input {
  width: 100%;
  :deep(.el-textarea__inner) {
    border-radius: 4px;
    resize: none;
    box-shadow: none;
    &:focus {
      box-shadow: none;
    }
  }
}

.button-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 10px;
}

.left-buttons {
  display: flex;
  gap: 10px;
}

.upload-button {
  margin-right: auto;
}

/* 自定义滚动条样式 */
::-webkit-scrollbar {
  width: 4px;
}

::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 2px;
}

::-webkit-scrollbar-track {
  background-color: transparent;
}

/* 移除之前的重复滚动条样式 */
.conversation-list::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar {
  display: none;
}

.conversation-list::-webkit-scrollbar-thumb,
.chat-messages::-webkit-scrollbar-thumb {
  display: none;
}

.conversation-list::-webkit-scrollbar-track,
.chat-messages::-webkit-scrollbar-track {
  display: none;
}

.logout-container {
  margin-top: auto;
  padding: 16px;
  border-top: 1px solid #e5e7eb;
}

.logout-container .el-button {
  width: 100%;
  justify-content: flex-start;
}

.ai-content {
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: inherit;
  margin: 0;
}

.attachments {
  margin-top: 10px;
}

.attachment-item {
  display: flex;
  align-items: center;
  margin: 5px 0;
  gap: 8px;
}

.file-size {
  color: #999;
  font-size: 12px;
}

.upload-preview {
  margin-bottom: 10px;
  padding: 8px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.file-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 6px 12px;
  margin-bottom: 4px;
  background-color: white;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.file-name {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.delete-file {
  padding: 2px;
  color: #909399;
}

.delete-file:hover {
  color: #f56c6c;
}
</style> 